/*  alig.c
    Copyright 2007 Helmar Wodtke
    License: MIT
    Purpose: Fixes for machines that require alignement for cells.
*/
#include <stdio.h>
#include "4p.h"

#ifdef ALIGNEMENT_FIX
# ifndef NETWORK_ORDER
cell _get(unsigned char *p) {
  if (((long)p & 3) == 0)
    return *(cell*)p;
#  ifdef ALIGNEMENT_WARNINGS
  fprintf(stderr, "unaligned GET(): %ld\n", (long)p);
#  endif
  return    *p
         + (*(p + 1) <<  8)
         + (*(p + 2) << 16)
         + (*(p + 3) << 24) ;
}
void _set(unsigned char *p, cell v) {
  if (((long)p & 3) == 0) {
    *(cell*)p = v;
    return;
  }
#  ifdef ALIGNEMENT_WARNINGS
  fprintf(stderr, "unaligned SET(): %ld\n", (long)p);
#  endif
  *p       = (unsigned char)  v;
  *(p + 1) = (unsigned char) (v >>  8);
  *(p + 2) = (unsigned char) (v >> 16);
  *(p + 3) = (unsigned char) (v >> 24);
  return;
}
# else
cell _get(unsigned char *p) {
  if ((p & 3) == 0)
    return *(cell*)p;
#  ifdef ALIGNEMENT_WARNINGS
  fprintf(stderr, "unaligned GET(): %ld\n", (long)p);
#  endif
  return   (*p       << 24)
         + (*(p + 1) << 16)
         + (*(p + 2) <<  8)
         +  *(p + 3) ;
}
void _set(unsigned char *p, cell v) {
  if ((p & 3) == 0) {
    *(cell*)p = v;
    return;
  }
#  ifdef ALIGNEMENT_WARNINGS
  fprintf(stderr, "unaligned SET(): %ld\n", (long)p);
#  endif
  *p       = (unsigned char) (v >> 24);
  *(p + 1) = (unsigned char) (v >> 16);
  *(p + 2) = (unsigned char) (v >>  8);
  *(p + 3) = (unsigned char)  v;
  return;
}
# endif
#endif
